import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/question_model.dart';
import '../models/answer_model.dart';

class QuestionService {
  final Box<QuestionModel> _questionBox = Hive.box<QuestionModel>('questions');
  final Box<AnswerModel> _answerBox = Hive.box<AnswerModel>('answers');
  final Uuid _uuid = Uuid();

  // 创建问题
  Future<QuestionModel> createQuestion({
    required String userId,
    required String content,
  }) async {
    final question = QuestionModel(
      id: _uuid.v4(),
      userId: userId,
      content: content,
      createdAt: DateTime.now(),
    );

    await _questionBox.put(question.id, question);
    return question;
  }

  // 获取问题
  QuestionModel? getQuestionById(String id) {
    return _questionBox.get(id);
  }

  // 更新问题
  Future<void> updateQuestion(QuestionModel question) async {
    await _questionBox.put(question.id, question);
  }

  // 删除问题
  Future<void> deleteQuestion(String id) async {
    // 删除问题下的所有回答
    final question = getQuestionById(id);
    if (question != null) {
      for (var answer in question.answers) {
        await _answerBox.delete(answer.id);
      }
    }
    await _questionBox.delete(id);
  }

  // 获取所有问题
  List<QuestionModel> getAllQuestions() {
    return _questionBox.values.toList();
  }

  // 获取热门问题
  List<QuestionModel> getHotQuestions() {
    return _questionBox.values.where((q) => q.isHot).toList();
  }

  // 获取用户的问题
  List<QuestionModel> getUserQuestions(String userId) {
    return _questionBox.values.where((q) => q.userId == userId).toList();
  }

  // 添加回答
  Future<AnswerModel> addAnswer({
    required String questionId,
    required String userId,
    required String content,
  }) async {
    final question = getQuestionById(questionId);
    if (question == null) {
      throw Exception('问题不存在');
    }

    final answer = AnswerModel(
      id: _uuid.v4(),
      questionId: questionId,
      userId: userId,
      content: content,
      createdAt: DateTime.now(),
    );

    await _answerBox.put(answer.id, answer);
    question.addAnswer(answer);
    await updateQuestion(question);

    return answer;
  }

  // 删除回答
  Future<void> deleteAnswer(String questionId, String answerId) async {
    final question = getQuestionById(questionId);
    if (question != null) {
      question.answers.removeWhere((a) => a.id == answerId);
      question.answerCount = question.answers.length;
      await updateQuestion(question);
    }
    await _answerBox.delete(answerId);
  }

  // 设置为热门问题
  Future<void> setHotQuestion(String id, bool isHot) async {
    final question = getQuestionById(id);
    if (question != null) {
      question.isHot = isHot;
      await updateQuestion(question);
    }
  }

  // 添加样例问答数据（开发测试用）
  Future<void> createSampleQuestionsAndAnswers(List<String> userIds) async {
    if (_questionBox.isEmpty && userIds.isNotEmpty) {
      // 确保至少有5个用户来创建样例问答
      if (userIds.length >= 5) {
        // 问题1
        final question1 = await createQuestion(
          userId: userIds[0],
          content: 'Essential diving gear?',
        );

        // 设置为热门问题
        await setHotQuestion(question1.id, true);

        // 为问题1添加回答
        await addAnswer(
          questionId: question1.id,
          userId: userIds[1],
          content:
              'For beginners, I recommend starting with: mask, snorkel, fins, wetsuit, buoyancy compensator, regulator, and a dive computer. Renting is a good option before investing in your own gear.',
        );

        await addAnswer(
          questionId: question1.id,
          userId: userIds[2],
          content:
              'Don\'t forget a good quality mask that fits properly! It\'s the most important piece of equipment for an enjoyable dive. Also, a dive watch with depth gauge is essential for tracking your time underwater.',
        );

        // 问题2
        final question2 = await createQuestion(
          userId: userIds[3],
          content: 'How to improve buoyancy?',
        );

        // 为问题2添加回答
        await addAnswer(
          questionId: question2.id,
          userId: userIds[4],
          content:
              'Practice proper breathing techniques - inhale normally and exhale slowly. Try buoyancy exercises like hovering and fin pivots during your dives. Also, make sure your weight is correctly distributed.',
        );

        await addAnswer(
          questionId: question2.id,
          userId: userIds[1],
          content:
              'Try the Buddha position - sit cross-legged underwater and try to maintain your position without touching the bottom. It\'s a great way to practice fine control of your buoyancy.',
        );

        // 问题3 (热门)
        final question3 = await createQuestion(
          userId: userIds[2],
          content: 'Prevent mask fogging?',
        );

        // 设置为热门问题
        await setHotQuestion(question3.id, true);

        // 为问题3添加回答
        await addAnswer(
          questionId: question3.id,
          userId: userIds[0],
          content:
              'I use a commercial anti-fog solution before every dive. Apply it to the dry mask, spread it around, then rinse lightly. Also, avoid touching the inside of your mask after applying.',
        );

        await addAnswer(
          questionId: question3.id,
          userId: userIds[3],
          content:
              'Baby shampoo works great as an affordable anti-fog solution! Mix a drop with some water in your mask, swish it around, and rinse lightly. It\'s gentle and highly effective.',
        );

        await addAnswer(
          questionId: question3.id,
          userId: userIds[4],
          content:
              'Spit works in a pinch! Just spit in your mask, rub it around the inside of the lens, and rinse lightly. It\'s an old diver\'s trick that actually works quite well.',
        );

        // 问题4
        final question4 = await createQuestion(
          userId: userIds[1],
          content: 'Best spots for marine photos?',
        );

        // 为问题4添加回答
        await addAnswer(
          questionId: question4.id,
          userId: userIds[2],
          content:
              'Look for protected marine areas with healthy coral reefs. Dawn and dusk dives often provide the best lighting for photography. Research locations known for specific marine life you want to capture.',
        );

        // 问题5 (热门)
        final question5 = await createQuestion(
          userId: userIds[4],
          content: 'Signs of decompression sickness?',
        );

        // 设置为热门问题
        await setHotQuestion(question5.id, true);

        // 为问题5添加回答
        await addAnswer(
          questionId: question5.id,
          userId: userIds[0],
          content:
              'Signs include joint pain, extreme fatigue, dizziness, tingling or numbness, shortness of breath, and confusion. If you experience these after diving, seek immediate medical attention and oxygen if available. Always dive conservatively and follow your dive tables or computer.',
        );
      }
    }
  }
}
